import { Effect, Reducer, Subscription } from 'umi';

export interface IndexModelState {
  name: string;
}

export interface IndexModelType {
  namespace: 'indexModel';
  state: IndexModelState;
  effects: {
    query: Effect;
  };
  reducers: {
    setName: Reducer<IndexModelState>;
  };
  subscriptions: {
    setup: Subscription;
  };
}

const IndexModel: IndexModelType = {
  namespace: 'indexModel',
  state: {
    name: 'testTs',
  },
  effects: {
    *query(_, { put }) {
      yield put({ type: 'setName', payload: { name: 'hello typescript' } });
    },
  },
  reducers: {
    setName(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/') {
          dispatch({
            type: 'query',
          });
        }
      });
    },
  },
};
export default IndexModel;
